package mysql

import "gorm.io/gorm"

type Cart struct {
	gorm.Model
	UserID     uint   `gorm:"type:int(11);not null;index;comment:用户id"`
	GoodsID    int64  `gorm:"type:int(11);not null;index;comment:商品id"`
	GoodsTitle string `gorm:"type:varchar(100);not null;index;;comment:商品标题"`
	GoodsPrice int64  `gorm:"type:int(11);not null;default:0;comment:商品单价"`
	GoodsNum   int64  `gorm:"type:int(11);not null;default:0;comment:数量"`
	Checked    int8   `gorm:"type:tinyint(1);not null;default:1;comment:1选中 2 未选中"`
}

//创建购物车

func (c *Cart) Create() error {

	return Db.Create(&c).Error
}

//购物车列表

func (c *Cart) CartList() (cartList []*Cart, err error) {
	err = Db.Where("user_id = ?", c.UserID).Find(&c).Error
	return
}

//修改

func (c *Cart) Update() error {
	return Db.Where("user_id = ?", c.UserID).Where("goods_id", c.GoodsID).Model(&c).UpdateColumn("goods_num", gorm.Expr("goods_num + ?", c.GoodsNum)).Error
}

//查询购物车是否存在

func (c *Cart) Exist() bool {
	result := Db.Where("user_id = ?", c.UserID).Where("goods_id = ?", c.GoodsID).First(&c)
	return result.RowsAffected > 0
}

//移除购物车

func (c *Cart) Delete() error {
	return Db.Delete(&c).Error
}

//清空购物车 通过用户id

func (c *Cart) DeleteAll() error {
	return Db.Where("user_id = ?", c.UserID).Delete(&c).Error
}

//获取选中的总价格总数量

func (c *Cart) GetCheckoutCardList() (cartList []*Cart, err error) {
	err = Db.Where("user_id = ? and checkout = 1", c.UserID).Find(&cartList).Error
	return
}

//查询选中商品列表

func (c *Cart) List() (cartList []*Cart) {
	err := Db.Where("user_id = ?", c.UserID).Where("checkout = 1").Find(&cartList).Error
	if err != nil {
		return nil
	} else {
		return cartList
	}
}
